import 'dart:convert';
import 'dart:ffi';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
//import 'package:flutter_app_upgrade/flutter_app_upgrade.dart';
import 'package:magic_car/UI/bottom_Menu_page.dart';
import 'package:magic_car/UI/userbottom_Menu_page.dart';
import 'package:magic_car/authinspcter/authinspectorder.dart';
import 'package:magic_car/authinspcter/imidiatesubmit.dart';
import 'package:magic_car/authinspcter/submitcarinfo.dart';
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/ensurancelist.dart';
import 'package:magic_car/baoxiu/ensurancestart.dart';
import 'package:magic_car/baoxiu/guarantee.dart';
import 'package:magic_car/baoxiu/insurance.dart';
import 'package:magic_car/jiance/b_guratee.dart';
import 'package:magic_car/jiance/b_mycar.dart';
import 'package:magic_car/jiance/b_order.dart';
import 'package:magic_car/jiance/guateencarlist.dart';
import 'package:magic_car/jiance/jiance_detail.dart';
import 'package:magic_car/jiance/jiance_rec.dart';
import 'package:magic_car/jiance/jianceorder.dart';
import 'package:magic_car/jiance/painter.dart';
import 'package:magic_car/jiance/queryhistory.dart';
import 'package:magic_car/jiance/uorder_page.dart';
import 'package:magic_car/user/acount.dart';
import 'package:magic_car/user/apply.dart';
import 'package:magic_car/user/applytest.dart';
import 'package:magic_car/user/bedituser.dart';
import 'package:magic_car/user/blance.dart';
import 'package:magic_car/user/blelib.dart';
import 'package:magic_car/user/bluedemo.dart';
import 'package:magic_car/user/bussaccount.dart';
import 'package:magic_car/user/bussinessgrouprecord.dart';
import 'package:magic_car/user/chargergroup.dart';
import 'package:magic_car/user/code.dart';
import 'package:magic_car/user/contact.dart';
import 'package:magic_car/user/distube.dart';
import 'package:magic_car/user/draw.dart';
import 'package:magic_car/user/drawrec.dart';
import 'package:magic_car/user/edituser.dart';
import 'package:magic_car/user/exam.dart';
import 'package:magic_car/user/exam_result.dart';
import 'package:magic_car/user/examrec.dart';
import 'package:magic_car/user/forgetpass.dart';
import 'package:magic_car/user/login.dart';
import 'package:magic_car/user/message.dart';
import 'package:magic_car/user/moneydetail.dart';
import 'package:magic_car/user/regist.dart';
import 'package:magic_car/user/set.dart';
import 'package:magic_car/user/start.dart';
import 'package:magic_car/user/bluetest.dart';
import 'package:magic_car/user/studyinfo.dart';
import 'package:magic_car/user/task.dart';
import 'package:magic_car/user/taskmoenydetail.dart';
import 'package:magic_car/user/taskwithdraw.dart';
import 'package:magic_car/util/FallbackCupertinoLocalisationsDelegate.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/chineseCupter.dart';

//import 'package:ota_update/ota_update.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
//import 'package:amap_base/amap_base.dart';
//import 'package:flutter_localizations/flutter_localizations.dart';
//import 'package:amap_location/amap_location.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
//import 'package:package_info/package_info.dart';
// import 'package:sharesdk/sharesdk_interface.dart';
import 'dart:io';
import 'package:url_launcher/url_launcher.dart';
// import 'package:progress_dialog/progress_dialog.dart';
//import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:magic_car/util/update_versions.dart';
// import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:magic_car/util/config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
//import 'package:sharesdk/sharesdk.dart';
void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(statusBarColor: Colors.transparent)
  );
 // AMapLocationClient.setApiKey("525046dad090259a9fe5fd02a417b04c");

 await SpUtil.getInstance();
  runApp(new MyApp());
}
// SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor:Colors.transparent);
// SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
 final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {




  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
     EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 1000)
      ..indicatorType = EasyLoadingIndicatorType.fadingCircle
      ..loadingStyle = EasyLoadingStyle.light
      ..indicatorSize = 45.0
      ..radius = 10.0
      ..fontSize = 13
      ..backgroundColor = Colors.green
      ..indicatorColor = Colors.yellow
      ..textColor = Colors.yellow
      ..maskColor = Colors.blue.withOpacity(0.5);
    return MaterialApp(
//  builder: (context, child) {
                 
// //return FlutterEasyLoading(child: child);
//                   // 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
//                   return MediaQuery(
//                     data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
//                     child: child,
//                   );
//                 },
      title: '车魔估众包',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try

        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
          primarySwatch:Colors.yellow
      ),
      home: MyHomePage(),
        builder: (context, child) {
                  return FlutterEasyLoading(child: child);

                  /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
                  // return MediaQuery(
                  //   data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                  //   child: child,
                  // );
                },
      localizationsDelegates: [
        //此处
        //
        ChineseCupertinoLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        const FallbackCupertinoLocalisationsDelegate(),
      ],
      supportedLocales: [
        //此处
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
      routes: {
        'index':(BuildContext context)=>new MyApp(),
        'uindex':(BuildContext context)=>new IOrderPage(),
        "jiance_rec":(BuildContext context)=>new OrderRecPage(),
        // "jianceorder_detail":(BuildContext context)=>new JIanceDetailPage(),
        "contact":(BuildContext context)=>new ContactPage(),
        "regist":(BuildContext context)=>new RegistPage(),
        "forgetpass":(BuildContext context)=>new ForgetPassPage('1'),
        "set":(BuildContext context)=>new SetPage(),
        "wallet":(BuildContext context)=>new AcountPage(),
        "bacount":(BuildContext context)=>new BAcountPage(),//车商、经纪人钱包
        "moneydetail":(BuildContext context)=>new MoneyRecPage(),
        "taskmoneydetail":(BuildContext context)=>new TaskMoneyRecPage(),
        "testrec":(BuildContext context)=>new ExamRecPage(),
       // "testrec":(BuildContext context)=>new ExamResultPage(),
        "draw":(BuildContext context)=>new DrawPage('1'),
        "drawrec":(BuildContext context)=>new DrawrecPage(),
        "taskdrawrec":(BuildContext context)=>new TaskDrawrecPage(),
        "csapply":(BuildContext context)=>new ApplyPage(),
        "code":(BuildContext context)=>new CodePage(),
        "exam":(BuildContext context)=>new ExamPage(),
        "applytest":(BuildContext context)=>new ApplyTestPage(),
        "upAsk":(BuildContext context)=>new UpAskPage(),
        'painter':(BuildContext context)=>new DemoApp(),
        'b_order':(BuildContext context)=>new BOrderRecPage(),
        'b_Gurateeorder':(BuildContext context)=>new BGurateOrderRecPage(),
        'mycar':(BuildContext context)=>new MycarPage(),
        'editinfo':(BuildContext context)=>new EditUserPage(),
        'bedituser':(BuildContext context)=>new BEditUserPage(),
        //BluePage
        'blue':(BuildContext context)=>new BluePages(),
        // 'blue':(BuildContext context)=>new BluePage(),
        // 'blue':(BuildContext context)=>new FlutterBlueApp(),
        'blance':(BuildContext context)=>new BlancePage(),
        'study':(BuildContext context)=>new StudyInfoPage(),
        'task':(BuildContext context)=>new TaskPage(),
        'message':(BuildContext context)=>new MessagePage(),
        'chargergroup':(BuildContext context)=>new ChargerGroupPage(),
        'chargergrouprec':(BuildContext context)=>new BussinessGroupRecPage(),
        'addauthcarinfo':(BuildContext context)=>new SubmitAuthcarPage(),
        'imdatesubmitcarinfo':(BuildContext context)=>new ImmidateSubmitAuthcarPage(),//快速下单
        'authinsprctororder':(BuildContext context)=>new AuthOrderRecPage(),
        'querycarinfopage':(BuildContext context)=>new QuerycarinfoPage(),//查询车辆历史信息
        'ensurancelist':(BuildContext context)=>new EnsuranceListPage(),//质保订单列表
        'ensurancestart':(BuildContext context)=>new EnsuranceStartPage(),//质保订单列表
        'gurateencar':(BuildContext context)=>new GurateencarPage()//质保车源列表
        
        // 'insurance_company':(BuildContext context)=>new Insurance_Page(),
        // 'brand':(BuildContext context)=>new BrandSelectRoute(),

        //"guarantee":(BuildContext context)=>new GuaranteePage(),

        //"login":(BuildContext context)=>new LoginPage(),
      },
      // localizationsDelegates: [
        
      //   GlobalMaterialLocalizations.delegate,
      //   GlobalWidgetsLocalizations.delegate,
      // ],
      // supportedLocales: [
      //   //此处
      //   locale: Locale('zh'),
      //   const Locale('zh', 'CH'),
      //   const Locale('en', 'US'),
      // ],

    );
  }
}
checkLogin() async{
  return StartPage();
//   SharedPreferences pref = await SharedPreferences.getInstance();
//  var islogin = pref.getString('islogin');
//  if(islogin=="1"){
//    return BotomeMenumPage();
//  }else
// return StartPage();
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 BaiduLocation _baiduLocation;
 
  LocationFlutterPlugin _locationPlugin = new LocationFlutterPlugin();
  static String _version;
  static String _flatform;
  static String _remoteVersion;//服务器当前版本
  String _customJson = '';
  String debugLable = 'Unknown';   /*错误信息*/
  final JPush jpush = new JPush();
  int _counter = 0;
  var loginState;
  var _role;

  get() async {
    var islogin;

    final prefs = await SharedPreferences.getInstance();
    islogin = prefs.getString("islogin");
    var role = prefs.getString("role");

    setState(() {
      loginState = islogin;
      _role = role;
    });
  }

  void checkLoginState() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var states = await prefs.getString('login');
    print('登录状态' + states);

    setState(() {
      loginState = states;
    });
  }



  @override
  void initState() {
     _locationPlugin.requestPermission();
  //动态申请定位权限

 // LocationFlutterPlugin.setApiKey("hHqbyRqLANLY1rL0EU5C16jfDEyRhoCp");
    // AppUpgrade.appUpgrade(
    //   context,
    //   _checkAppInfo(),
    //   iosAppId: 'id88888888',
    // );
    // TODO: implement initState
    super.initState();
    // checkVersions();
    // initXUpdate();
    // checkVersions();
    _initFluwx();
    //initShareSDK();
    get();
    jpush.getRegistrationID().then((rid) async{

      print('---->rid:${rid}');
      SharedPreferences pref = await SharedPreferences.getInstance();
      pref.setString('registeid', rid);
    });
    jpush.setup(appKey: '1d82958cf8f5495ac116bb88' ,channel: 'developer-default',production: true,debug: true);
    /// iOS千万记得加上这句！！！！！！要不没用
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));
    jpush.addEventHandler(
      onReceiveNotification: (Map<String, dynamic> message) async {
        // var fireDate = DateTime.fromMillisecondsSinceEpoch(DateTime.now().millisecondsSinceEpoch + 3000);
        //                 var localNotification = LocalNotification(
        //                   id: 234,
        //                   title: '我是推送测试标题',
        //                   buildId: 1,
        //                   content: '看到了说明已经成功了',
        //                   fireTime: fireDate,
        //                   subtitle: '一个测试',
        //                 );
        // jpush.sendLocalNotification(localNotification).then((value) => {});
        print('收到消息');
        print(message);
      },
      onOpenNotification: (Map<String, dynamic> message) async {
        /// 点击通知栏消息，在此时通常可以做一些页面跳转等
        print('点击通知');
        print(message);
        final result =
            json.decode(message["extras"]["cn.jpush.android.EXTRA"].toString());
        if (result["data"]["type"] == "news") {
          //String order_id = result["order_id"].toString();
          spikToDetailJpush("1",1);
        }
      },
    );
    


  }

    spikToDetailJpush(orderid,type) async {
  //type 1 为普通消息进入消息列表
  //
  // 
    if(type==1){
      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return MessagePage();
      }));
//      Navigator.of(navigatorKey.currentState.overlay.context)
//         .push(MaterialPageRoute(builder: (context) {
//       return MessagePage();
//       //  return CarListPage();
// // return JPUSHMessageDetail(id: massageId);
//     }));
    }
  }
  //初始化微信组件
  _initFluwx() async {
    // Fluwx.registerApp(RegisterModel(appId: Config.wx_appid, doOnAndroid: true, doOnIOS: true));
    await registerWxApi(
        appId: Config.wx_appid,
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://app.chemogu1688.com/");
    var result = await isWeChatInstalled;
    print("is installed $result");

  }

  initShareSDK() {
    // ShareSDKRegister register = ShareSDKRegister();
    // register.setupWechat(
    //       Config.wx_appid,Config.wx_secrect);
    // ShareSDK.regist(register);
  }

  // void initXUpdate() {
  //   //初始化更新组件
  //   if (Platform.isAndroid) {
  //     FlutterXUpdate.init(
  //       ///是否输出日志
  //         debug: true,
  //         ///是否使用post请求
  //         isPost: false,
  //         ///post请求是否是上传json
  //         isPostJson: false,
  //         ///是否开启自动模式
  //         isWifiOnly: false,
  //         ///是否开启自动模式
  //         isAutoMode: false,
  //         ///需要设置的公共参数
  //         supportSilentInstall: false,
  //         ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
  //         enableRetry: false
  //     ).then((value) {
  //       //updateMessage("初始化成功: $value");
  //     }).catchError((error) {
  //       print(error);
  //     });

  //     FlutterXUpdate.setErrorHandler(
  //         onUpdateError: (Map<String, dynamic> message) async {
  //           print(message);
  //           setState(() {
  //             // _message = "$message";
  //           });
  //         });
  //   } else {
  //     //updateMessage("ios暂不支持XUpdate更新");
  //   }
  // }



  // Future<AppUpgradeInfo> _checkAppInfo() {
  // return Future.value(AppUpgradeInfo(
  //   title: '新版本V1.1.1',
  //   contents: [
  //     '1、支持立体声蓝牙耳机，同时改善配对性能',
  //     '2、提供屏幕虚拟键盘',
  //     '3、更简洁更流畅，使用起来更快',
  //     '4、修复一些软件在使用时自动退出bug',
  //     '5、新增加了分类查看功能'
  //   ],
  //   apkDownloadUrl: 'https://ymcd.xiaozhujc.com/cdbMcnWebserver/public/app-release.apk',
  //   force: false,
  // ));
  // }
  // void checkVersions ()async{
  //   PackageInfo packageInfo = await PackageInfo.fromPlatform();
  //   _version = packageInfo.version;
  //   print('当前应用版本');
  //   print(_version);
  //   Map<String, String> map = new Map();
  //   HttpHelper.post(HttpHelper.API_Version, (data) {
  //     if (data != null) {
  //       print(data);
  //       // if(_version!=data['info']['app_version']){
  //       //   //有新版本
  //       //   //_showNewVersionAppDialog();
  //       FlutterXUpdate.checkUpdate(url: 'https://ylz.9ok6.com/app/cmg_api.php?i=16&r=cmgapi.remoteversion',themeColor: '#FFFFAC5D');
  //       // }

  //     }
  //   }, params: map);

  // }






  ///检查是否有权限
  checkPermission() async {
    //检查是否已有读写内存权限
    // PermissionStatus status = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);

    // //判断如果还没拥有读写权限就申请获取权限
    // if(status != PermissionStatus.granted){
    //   var map = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
    //   if(map[PermissionGroup.storage] != PermissionStatus.granted){
    //     return false;
    //   }
    // }
  }

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }
// @override
//   Widget build(BuildContext context) {
//      var bodycontent ;
//     if (loginState == "1") {
//       if (_role == "1")
//         bodycontent= UBotomeMenumPage();
//       else
//         bodycontent=  BotomeMenumPage();
//     } else
//       bodycontent=  StartPage();


//       return MaterialApp(
//         home: bodycontent,
//         localizationsDelegates: <LocalizationsDelegate<dynamic>>[
//         ChineseCupertinoLocalizations.delegate, // 这里加上这个,是自定义的delegate

//         DefaultCupertinoLocalizations.delegate, // 这个截止目前只包含英文

//         // 下面两个是Material widgets的delegate, 包含中文
//         GlobalMaterialLocalizations.delegate,
//         GlobalWidgetsLocalizations.delegate,
//       ],
//       supportedLocales: [
//         const Locale('en', 'US'), // English
//         const Locale('zh', 'Hans'), // China
//         const Locale('zh', ''), // China
//         // ... other locales the app supports
//       ],


//       );
//   }
  
  @override
  Widget build(BuildContext context) {

    if (loginState == "1") {
      if (_role == "1")
        return new UBotomeMenumPage();
      else
        return new BotomeMenumPage();
    } else
      return new StartPage();
  }

}
